<template>
  <div class="traffic-jam">
    <el-alert v-if="error" :title="error" type="error" show-icon class="mb-4" @close="error = ''" />
    <el-row :gutter="20">
      <!-- 左侧表格 -->
      <el-col :span="15">
        <el-card>
          <template #header>
            <div class="card-header">
              <div class="header-left">
                <el-radio-group v-model="currentRoadType" @change="handleRoadTypeChange">
                  <el-radio-button :value="0">全部道路</el-radio-button>
                  <el-radio-button :value="1">快速/高速道路</el-radio-button>
                  <el-radio-button :value="2">普通道路</el-radio-button>
                </el-radio-group>
                <el-radio-group
                  v-model="currentTimeType"
                  class="ml-4"
                  @change="handleTimeTypeChange"
                >
                  <el-radio-button :value="0">实时</el-radio-button>
                  <el-radio-button :value="1">昨天</el-radio-button>
                </el-radio-group>
              </div>
              <span class="update-time">更新时间: {{ updateTime }}</span>
            </div>
          </template>

          <el-table :data="rankData" v-loading="loading" @row-click="handleRowClick">
            <el-table-column type="index" label="排名" width="70" align="center" />
            <el-table-column prop="name" label="道路名称" width="140" />
            <el-table-column prop="direction" label="方向" header-align="center" />
            <el-table-column label="拥堵延时指数" width="110" align="center">
              <template #default="{ row }">
                <el-tag :type="getCongestionLevel(row.index)">{{ row.index }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="speed" label="速度" width="70" align="center" />
            <el-table-column prop="travelTime" label="旅行时间" width="80" align="center" />
            <el-table-column prop="delayTime" label="延误时间" width="80" align="center" />
          </el-table>
          <div class="table-footer">
            *注：数据样本截取自早晚高峰时段；速度单位：公里/小时；长度单位：公里；时间单位：分钟
          </div>
        </el-card>
      </el-col>

      <!-- 右侧内容 -->
      <el-col :span="9">
        <!-- 地图卡片 -->
        <el-card class="mb-4 map-card">
          <div class="map-wrapper">
            <BMap
              :center="mapCenter"
              :zoom="mapZoom"
              :minZoom="mapMinZoom"
              mapType="BMAP_NORMAL_MAP"
              v-bind="mapSetting"
              ref="baiduMap"
            >
              <BPolyline
                v-if="pathArray"
                :path="pathArray"
                :stroke-color="strokeColor"
                :stroke-opacity="1"
                :stroke-weight="5"
              />
              <BMarker
                v-if="markerData"
                v-for="(item, index) in markerData"
                :key="index"
                :position="item.position"
                :icon="item.icon"
              />
            </BMap>
          </div>
        </el-card>

        <!-- 趋势图卡片 -->
        <el-card class="map-card">
          <div class="chart-wrapper" ref="trendChartRef"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch } from "vue";
import { getSpecificTrafficJam, getRoadDetail } from "@/apis/TrafficJam";
import { BMap, BPolyline, MapProps } from "vue3-baidu-map-gl";
import * as echarts from "echarts";

type CongestionLevelType = "primary" | "success" | "warning" | "danger";

interface RoadRankItem {
  name: string; // 道路名称
  dir: string; // 道路方向
  index: number; // 拥堵延时指数
  speed: number; // 速度
  travelTime: number; // 旅行时间
  delayTime: number; // 延误时间
  coords: Array<{ lon: number; lat: number }>; // 道路坐标
  id: string; // 道路id
  length: number; // 道路长度
  number: number; // 拥堵排名
}

interface BMapInstance {
  setMapStyleV2: (style: { styleId: string }) => void;
}

interface RankDataItem {
  name: string;
  direction: string;
  index: number;
  speed: number;
  travelTime: number;
  delayTime: number;
}

interface TrendData {
  time: string;
  index: number;
}

interface MapCenter {
  lng: number;
  lat: number;
}

const currentRoadType = ref(0);
const currentTimeType = ref(0);
const updateTime = ref("");
const loading = ref(false);
const rankData = ref<RankDataItem[]>([]);
const trendData = ref<TrendData[]>([]);
const trendChartRef = ref();
let trendChart: echarts.ECharts | null = null;
const REFRESH_INTERVAL = 5 * 60 * 1000; // 5分钟刷新一次
let refreshTimer: number | null = null;
const error = ref("");

const pathArray = ref<Array<{ lng: number; lat: number }> | null>(null);
const markerData = ref<Array<{ position: { lng: number; lat: number }; icon: string }> | null>(
  null
);

// 地图相关的响应式数据
const mapCenter = ref<MapCenter>({ lng: 114.305393, lat: 30.593099 }); // 武汉市中心坐标
const baiduMap = ref<BMapInstance | null>(null);
const mapZoom = ref(11);
const mapMinZoom = ref(3);
const strokeColor = ref("#000");

// 地图基础配置
const mapSetting = ref<MapProps>({
  enableDragging: true,
  enableInertialDragging: true,
  enableScrollWheelZoom: true,
  enableContinuousZoom: true,
  enableResizeOnCenter: true,
  enableDoubleClickZoom: true,
  enableKeyboard: true,
  enablePinchToZoom: true,
  enableAutoResize: true,
  enableTraffic: true,
});

// 获取拥堵数据
const fetchTrafficData = async () => {
  loading.value = true;
  error.value = "";
  try {
    const res = await getSpecificTrafficJam(currentRoadType.value, currentTimeType.value);

    if (res.success && res.data) {
      rankData.value = res.data.tableData.map((item: RoadRankItem) => ({
        name: item.name,
        direction: item.dir,
        index: item.index,
        speed: item.speed,
        travelTime: item.travelTime,
        delayTime: item.delayTime,
        coords: item.coords,
        id: item.id,
        length: item.length,
        number: item.number,
      }));
      updateTime.value = res.data.updateTime;
    }
  } catch (error) {
    error.value = "网络请求失败，请稍后重试";
  } finally {
    loading.value = false;
  }
};

// 获取拥堵等级
const getCongestionLevel = (index: number): CongestionLevelType => {
  if (index >= 3.5) return "danger";
  if (index >= 2.5) return "warning";
  if (index >= 1.5) return "primary";
  return "success";
};

// 启动自动刷新
const startAutoRefresh = () => {
  if (refreshTimer) return;
  refreshTimer = window.setInterval(() => {
    if (currentTimeType.value === 0) {
      // 只在实时模式下自动刷新
      fetchTrafficData();
    }
  }, REFRESH_INTERVAL);
};

// 停止自动刷新
const stopAutoRefresh = () => {
  if (refreshTimer) {
    window.clearInterval(refreshTimer);
    refreshTimer = null;
  }
};

// 处理时间类型变化
const handleTimeTypeChange = () => {
  fetchTrafficData();
  if (currentTimeType.value === 1) {
    stopAutoRefresh();
  } else {
    startAutoRefresh();
  }
};

// 初始化趋势图
const initTrendChart = () => {
  if (trendChartRef.value) {
    trendChart = echarts.init(trendChartRef.value);
    const option: echarts.EChartsOption = {
      title: {
        text: "拥堵延时指数趋势",
        left: "center",
      },
      grid: {
        left: "6%",
        right: "6%",
        bottom: "10%",
        top: "15%",
        containLabel: true,
      },
      tooltip: {
        trigger: "axis",
        formatter: "{b}<br/>拥堵指数: {c}",
      },
      xAxis: {
        type: "category",
        data: [],
        axisLine: {
          lineStyle: {
            color: "#DCDFE6",
          },
        },
      },
      yAxis: {
        type: "value",
        min: 0,
        max: 5,
        splitLine: {
          lineStyle: {
            type: "dashed",
            color: "#E4E7ED",
          },
        },
      },
      series: [
        {
          data: [],
          type: "line",
          smooth: true,
          lineStyle: {
            color: "#409EFF",
            width: 3,
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              {
                offset: 0,
                color: "rgba(64, 158, 255, 0.8)",
              },
              {
                offset: 1,
                color: "rgba(64, 158, 255, 0.1)",
              },
            ]),
            shadowColor: "rgba(64, 158, 255, 0.2)",
            shadowBlur: 10,
          },
        },
      ],
    };
    trendChart.setOption(option);
  }
};

// 更新趋势图数据
const updateTrendChart = async (params: {
  roadType: number;
  timeType: number;
  cityCode: string;
  lineCode: string;
}) => {
  if (!trendChart) return;

  const { data, success } = await getRoadDetail(params);

  if (!success || !data) return;

  let maxValue = 0;

  const times = data.map((item) => formatTimestamp(item[0]));
  const values = data.map((item) => {
    maxValue = Math.max(maxValue, item[1]);
    return item[1];
  });

  trendChart.setOption({
    xAxis: {
      data: times,
      axisLabel: {
        rotate: 45,
        formatter: (value: string) => {
          return value.split(" ")[1]; // 只显示时间部分
        },
      },
    },
    yAxis: {
      min: 0,
      max: maxValue,
    },
    series: [
      {
        data: values,
      },
    ],
  });
};

// 将时间戳转换为格式化的日期时间字符串
const formatTimestamp = (timestamp: number): string => {
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  const hours = String(date.getHours()).padStart(2, "0");
  const minutes = String(date.getMinutes()).padStart(2, "0");
  const seconds = String(date.getSeconds()).padStart(2, "0");

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

const handleRowClick = (row: RoadRankItem) => {
  // 转换坐标数据
  pathArray.value = row.coords.map((item) => ({
    lng: Number(item.lon),
    lat: Number(item.lat),
  }));

  // 设置线段颜色
  if (row.index >= 3.5) strokeColor.value = "#FF4D4F"; // 红色
  else if (row.index >= 2.5) strokeColor.value = "#FFA921"; // 橙色
  else if (row.index >= 1.5) strokeColor.value = "#00BFFF"; // 蓝色
  else if (row.index >= 1) strokeColor.value = "#52C41A"; // 绿色

  // 设置地图中心点
  mapCenter.value = {
    lng: Number(row.coords[0].lon + row.coords[row.coords.length - 1].lon) / 2,
    lat: Number(row.coords[0].lat + row.coords[row.coords.length - 1].lat) / 2,
  };

  // 设置地图缩放级别
  mapZoom.value = 12;

  // 标记起点终点
  markerData.value = [
    { position: { lng: Number(row.coords[0].lon), lat: Number(row.coords[0].lat) }, icon: "start" },
    {
      position: {
        lng: Number(row.coords[row.coords.length - 1].lon),
        lat: Number(row.coords[row.coords.length - 1].lat),
      },
      icon: "end",
    },
  ];

  updateTrendChart({
    roadType: currentRoadType.value,
    timeType: currentTimeType.value,
    cityCode: "420100",
    lineCode: row.id,
  });
};

// 处理道路类型变化
const handleRoadTypeChange = () => {
  fetchTrafficData();
};

// 处理窗口大小变化的函数
const handleResize = () => trendChart?.resize();

onMounted(() => {
  fetchTrafficData();
  initTrendChart();
  window.addEventListener("resize", handleResize);
  startAutoRefresh();
});

onUnmounted(() => {
  trendChart?.dispose();
  window.removeEventListener("resize", handleResize);
  stopAutoRefresh();
});
</script>

<style lang="scss" scoped>
.traffic-jam {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .header-left {
      display: flex;
      gap: 16px;
    }

    .update-time {
      color: #606266;
      font-size: 14px;
    }
  }

  .map-card {
    position: relative;
    height: 40vh;

    .map-wrapper {
      height: 40vh;
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;

      :deep(.bmap-container) {
        height: 100% !important;
        width: 100% !important;
      }
    }
  }

  .chart-wrapper {
    height: 40vh;
  }

  .table-footer {
    margin-top: 12px;
    font-size: 12px;
    color: #909399;
    line-height: 1.4;
  }

  :deep(.el-card__header) {
    padding: 12px 20px;
  }

  .mb-4 {
    margin-bottom: 16px;
  }
}

.ml-4 {
  margin-left: 16px;
}
</style>
